import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { info, success,error, Button, Link, TweetInput,MulSelect,Modal,Tooltip } from '../../ui-components'
import Feed from './Feed'
import util from '../../util'
import style from './style.newsfeed'
import twemoji from 'twemoji'
import { findDOMNode } from 'react-dom'

import { clearAtList, fetchAtList } from '../../actions/home.action'
import { searchTeamsAndUsers,clearTeamsAndUsers } from '../../actions/okr.action'
import * as kudosAction from '../../actions/kudos.action'

import cx from 'classnames';
import KudoItem from './KudoItem';

export default
@connect(({ newsFeed,app,okr,kudos }) => ({ newsFeed,app,okr,kudos }),dispatch => ({actions: bindActionCreators({...kudosAction, searchTeamsAndUsers,clearTeamsAndUsers, fetchAtList, clearAtList}, dispatch)}))
class NewsFeed extends React.Component {
    constructor(props) {
        super(props);
        const {
            medal,
        } = props.kudos;
        const {
            personalRewardMedalVOs = [],
            teamRewardMedalVOs = [],
        } = medal;
        this.state = {
            scrollTop: '',
            loading: false,
            complete: false,
            empty: false,
            addFeed: true,
            userSelect: [],
            teamSelect: [],
            userKudo: personalRewardMedalVOs.length? [personalRewardMedalVOs[0]] : [],
            teamKudo: teamRewardMedalVOs.length? [teamRewardMedalVOs[0]]: [],
            tabIndex: 0,
            inputDisable: true,
            isShowModal: false,
        }
    }
    willUnmount = false

    // 页码, 从1开始
    pageNumber = 1
    // 每页加载数目
    pageSize = 30

    bindScroll = false

    fetchFeeds() {
        if (this.willUnmount) return
        this.setState({
            loading: true
        })
        if (this.willUnmount) return
        this.props.fetchFeeds({
            pageSize: this.pageSize,
            pageNumber: this.pageNumber
        }, () => {
            this.pageNumber += 1
            if (this.willUnmount) return
            this.setState({
                loading: false
            })
        })
    }

    componentWillReceiveProps(props) {
        if ((!this.props.root && props.root) ||
            (this.props.root && props.root && !this.bindScroll)) {
            util.bind(findDOMNode(props.root), 'scroll', this.onScroll)
            this.bindScroll = true
        }

        if (typeof props.newsFeed.data.amount === 'number' && util.type(props.newsFeed.data.feeds) === 'array') {
            if (props.newsFeed.data.amount == props.newsFeed.data.feeds.length) {
                this.setState({
                    complete: true
                })
                if (props.newsFeed.data.amount == 0) {
                    this.setState({
                        empty: true
                    })
                }
            }
        }

        const {
            medal,
        } = this.props.kudos;
        const {
            amount = 0,
        } = medal;
        const {
            medal: nextMedal,
        } = props.kudos;
        const {
            amount: nextAmount = 0,
        } = nextMedal;
        if(amount !== nextAmount){
            const {
                personalRewardMedalVOs = [],
                teamRewardMedalVOs = [],
            } = nextMedal;
            this.setState({
                userKudo: personalRewardMedalVOs.length? [personalRewardMedalVOs[0]] : [],
                teamKudo: teamRewardMedalVOs.length? [teamRewardMedalVOs[0]]: [],
            })
        }

    }

    componentDidMount() {
        this.fetchFeeds()
        this.props.actions.fetchMedal();
        this.props.actions.fetchQuotaInfo();
    }

    componentWillUnmount() {
        util.unbind(findDOMNode(this.props.root), 'scroll', this.onScroll)
        this.props.resetNewsFeed()
    }
    handleUserSelect = (list) => {
        const {
            personalQuota,
            usedPersonalQuota,
        } = this.props.kudos.quotaInfo;
        const length = personalQuota - usedPersonalQuota > 0 ? (personalQuota - usedPersonalQuota): 0;
        if(list.length > length) {
            error('你的个人赞赏勋章额度已用完');
        }
        this.setState({
            userSelect: list.slice(0, length),
        })
    }
    handleTeamSelect = (list) => {
        this.setState({
            teamSelect: list.length ? [list.pop()]:[]
        })
    }
    onScroll = () => {
        util.bus.emit('newsfeed:scroll')
    }

    handleSubmit({ content, images, selectMap }, cb) {
        this.setState(
            {
                feedOrrewardType:2
            })
        let matches = []
        const match = content.match(/@[^@\s\n]+/g)
        if (match) matches = match.map(match => match.slice(1))

        const atUsers = matches
            .filter(name => selectMap[name])
            .map(name => selectMap[name])
        const { profile } = this.props;
        // encode emoji
        //content = content.replace(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g, (match, whole) => whole.replace(match, encodeURIComponent(match)))

        this.setState({
            addFeed: false
        })

        info('发布中...', true)

        this.props.addFeed({
            likeNumber: 0,
            commentNumber: 0,
            feedOrrewardType:2,
            isLikable: 1,
            isDeletable:1,
            feedUser: profile,
            content,
            images,
            atUsers
        }, () => {
            success('发布成功!')
            this.setState({
                addFeed: true,
            })
            this.setState({
                loading: true
            })
            this.props.fetchFeeds({
                pageSize: 30,
                pageNumber: 1
            }, () => {
                this.pageNumber += 1
                this.setState({
                    loading: false
                })
            })
            cb()
        })
    }

    renderFeeds(list) {
        if (util.isNull(list)) return null
        return (
            <ul className={style.feeds}>
                {
                    list.map((feed, i) => (
                        <Feed
                            {...this.props}
                            {...feed}
                            key={i}
                        />
                    ))
                }
            </ul>
        )
    }
    clickTab = (index) => {
        this.setState({
            tabIndex: index
        })
    }
    selectKudo = (type, item) => {
        if(type === 0){
            this.setState({
                userKudo: [item],
            })
        }else{
            this.setState({
                teamKudo: [item],
            })
        }
    }
    submitKudo = () => {
        this.refs.kudoTweetInput.handleSubmit();
    }
    submitKudoInput = ({ content, images, selectMap }, cb) => {
        let matches = []
        const {
            tabIndex,
            userSelect,
            teamSelect,
            userKudo,
            teamKudo,
        } = this.state;
        const match = content.match(/@[^@\s\n]+/g)
        if (match) matches = match.map(match => match.slice(1))

        const atUsers = matches
            .filter(name => selectMap[name])
            .map(name => selectMap[name])
        const { profile } = this.props

        this.setState({
            addFeed: false
        })

        info('发布中...', true)

        const {
            medal,
        } = this.props.kudos;
        const {
            amount = 0,
        } = medal;
        const {
            personalRewardMedalVOs = [],
            teamRewardMedalVOs = [],
        } = medal;

        this.props.addFeed({
            likeNumber: 0,
            commentNumber: 0,
            feedOrrewardType:this.state.tabIndex,
            isLikable: 1,
            isDeletable:0,
            feedUser: profile,
            content,
            images,
            atUsers,
            rewardType: tabIndex,
            rewardeeIds: tabIndex === 0 ? userSelect.map(v =>{ return {idValue: v.userId}}) : teamSelect.map(v => {return {idValue: v.teamId}}),
            rewardMedalId: (tabIndex === 0 ? userKudo : teamKudo).map(v => {return {idValue: v.rewardMedalId}}),
            rewardVO: {
                rewardMedalListVO: {
                    personalRewardMedalVOs: tabIndex === 0 ? userKudo : [],
                    teamRewardMedalVOs:  tabIndex === 1 ? teamKudo : [],
                },
                rewardType: this.state.tabIndex,
                rewardedTeams: tabIndex === 1 ? teamSelect : [],
                rewardedUsers: tabIndex === 0 ? userSelect : [],
            }
        }, () => {
            success('发布成功!')
            this.setState({
                addFeed: true,
                userSelect: [],
                teamSelect: [],
                userKudo: personalRewardMedalVOs.length? [personalRewardMedalVOs[0]] : [],
                teamKudo: teamRewardMedalVOs.length? [teamRewardMedalVOs[0]]: [],
                inputDisable: true,
            })
            cb();
            this.props.actions.fetchQuotaInfo();
        })
    }
    handlePublicSubmit = () => {
        this.refs.publicTweetInput.handleSubmit();
        this.setState({
            isShowModal: false,
        })
    }
    render() {
        const { data } = this.props.newsFeed
        const { feeds, amount } = data
        const fetchBtn = {
            disabled: this.state.loading || this.state.complete,
            label: this.state.loading? '加载中...': (this.state.complete && !this.state.NULL)? '没有更多动态了...': this.state.NULL? '还没有数据哦~~': '点击加载更多'
        }
        const { atList } = this.props.app;
        const {
            tabIndex,
            teamSelect,
            userSelect,
            userKudo,
            teamKudo,
        } = this.state;
        const {
            teamVOs = []
        } = this.props.okr.search || {};
        const {
            medal,
            quotaInfo,
        } = this.props.kudos;
        const {
            personalQuota,
            usedPersonalQuota,
            teamQuota,
            usedTeamQuota,
        } = quotaInfo;
        const {
            personalRewardMedalVOs = [],
            teamRewardMedalVOs = [],
        } = medal;
        const flag = tabIndex === 0 ?
            personalQuota - usedPersonalQuota > 0 && !!userSelect.length && !!userKudo.length
            :
            teamQuota - usedTeamQuota > 0 && !!teamSelect.length && !!teamKudo.length;
        const {
            profile
        } = this.props.app;
        const {
            roleNameList = []
        } = profile||{};
        const kudoDisabled = tabIndex === 0 ?
            personalQuota - usedPersonalQuota <= 0
            : teamQuota - usedTeamQuota <= 0;
        return (
            <div className={style.root}>
                <div className={style['left']}>
                    <div className={style['left-title']}>
                        赞赏墙
                        {
                            ~roleNameList.indexOf("orgAdmin") || ~roleNameList.indexOf('HR') ?
                                <Button
                                    className={style['left-btn']}
                                    label={'发公告'}
                                    onClick={() => {this.setState({isShowModal: true})}}
                                />
                                : null
                        }

                    </div>
                    <div className={style['left-box']}>
                        {/*

            */}
                        { this.renderFeeds(feeds) }
                        <Button
                            className={style['fetch-btn']}
                            {...fetchBtn}
                            white
                            onClick={::this.fetchFeeds}/>
                    </div>
                </div>
                <div className={style['right']}>
                    <div className={cx({
                        [style['right-tab']]: true,
                        [style['right-active']]: tabIndex === 0
                    })} onClick={this.clickTab.bind(this,0)}>个人<span></span></div>
                    <div className={cx({
                        [style['right-tab']]: true,
                        [style['right-tab2']]: true,
                        [style['right-active']]: tabIndex === 1
                    })} onClick={this.clickTab.bind(this,1)}>团队<span></span></div>
                    <div className={style['right-box']}>
                        <div className={style['invited-search']}>
                            {
                                tabIndex === 0 ?
                                    <MulSelect
                                        placeholder="赞赏对象"
                                        width={'385px'}
                                        value={[...this.state.userSelect]}
                                        onFocus={e => {
                                            let value = e.target.value;
                                            if (value)
                                                this.props.actions.fetchAtList({
                                                    keyword: value,
                                                    type: 2
                                                });
                                            else
                                                this.props.actions.clearAtList();
                                        }}
                                        fetch={value => {
                                            if (value)
                                                this.props.actions.fetchAtList({
                                                    keyword: value,
                                                    type: 2
                                                });
                                            else
                                                this.props.actions.clearAtList();
                                        }}
                                        getItemAttrs={(item) => {
                                            return {
                                                label: item.fullName,
                                                img: item.avatarUrl,
                                            }
                                        }}
                                        onSelect={this.handleUserSelect}
                                        options={atList}
                                        excludeList={[...this.state.userSelect,this.props.app.profile]}
                                    />
                                    :
                                    <MulSelect
                                        placeholder="赞赏团队"
                                        width={'385px'}
                                        value={[...this.state.teamSelect]}
                                        onFocus={e => {
                                            let value = e.target.value;
                                            if (value)
                                                this.props.actions.fetchAtList({
                                                    keyword: value,
                                                    type: 2
                                                });
                                            else
                                                this.props.actions.clearAtList();
                                        }}
                                        fetch={value => {
                                            if(value)
                                                this.props.actions.searchTeamsAndUsers({
                                                    keyword: value,
                                                    type: 1
                                                });
                                            else
                                                this.props.actions.clearTeamsAndUsers();
                                        }}
                                        getItemAttrs={(item) => {
                                            return {
                                                label: item.teamName,
                                            }
                                        }}
                                        noImg
                                        onSelect={this.handleTeamSelect}
                                        options={teamVOs}
                                        filter={(arr, exclude) => arr.filter(item => exclude.every(v => v.teamId != item.teamId))}
                                        item={({teamName}, attrs) => {
                                            return (
                                                <li {...attrs} onMouseDown={util.preventDefaultEvent/*组织默认事件，使焦点留在父元素的input中*/}>
                                                    <span>{ teamName }</span>
                                                </li>
                                            )
                                        }}
                                    />
                            }
                        </div>
                        <TweetInput
                            ref={'kudoTweetInput'}
                            handleFileChange={ (file, success) => {
                                // 请求上传地址
                                this.props.requestFeedImagesUploadUrl(res => {
                                    // 上传图片
                                    this.props.fileUpload({
                                        file: file.file.file,
                                        url: res.data.url,
                                        cb: () => {
                                            success({
                                                id: file.id,
                                                uuid: res.data.uuid,
                                                url: file.file.dataURL
                                            })
                                        }
                                    })
                                })
                            }}
                            onSubmit={this.submitKudoInput}
                            disabled={!this.state.addFeed || kudoDisabled}
                            atList={this.props.atList}
                            fetchAtList={keyword => this.props.fetchAtList({ keyword, type: 4 })}
                            label="说点什么.."
                            pic
                            multi
                            noBtn
                            checkDisable={(flag) => {this.setState({inputDisable: flag})}}
                        />
                        <div style={{margin: '10px 0 5px'}}>选择勋章:</div>
                        <div>
                            {
                                (tabIndex === 0 ? personalRewardMedalVOs : teamRewardMedalVOs).map((v,i) => {
                                    return <KudoItem active={~(tabIndex === 0 ? userKudo : teamKudo).findIndex(item => item.rewardMedalId === v.rewardMedalId)} item={v} key={i} onClick={this.selectKudo.bind(this,tabIndex,v)} />;
                                })
                            }
                        </div>
                        <div className={style['tweet-info']}>
                            {
                                tabIndex === 0 ?
                                    `您本月个人赞赏勋章额度为:${personalQuota}枚，剩余${personalQuota - usedPersonalQuota > 0 ? personalQuota - usedPersonalQuota : 0}枚`
                                    :
                                    `您本月团队赞赏勋章额度委:${teamQuota}枚，剩余${teamQuota - usedTeamQuota > 0 ? teamQuota - usedTeamQuota : 0}枚`
                            }
                        </div>
                        <div style={{display: 'right',marginTop: '20px',textAlign: 'right'}}>
                            {
                                kudoDisabled ?
                                    <Tooltip tip={'您的赞赏勋章额度已用完'} arrow={'top'} className={style['tip']}>
                                        <Button
                                            className={style['right-btn']}
                                            label={'发赞赏'}
                                            disabled={this.state.inputDisable || !flag}
                                            onClick={this.submitKudo}
                                        />
                                    </Tooltip>
                                    :<Button
                                        className={style['right-btn']}
                                        label={'发赞赏'}
                                        disabled={this.state.inputDisable || !flag}
                                        onClick={this.submitKudo}
                                    />
                            }

                        </div>
                        {kudoDisabled ?
                            <div className={style['kudo-disabled']}></div>
                            :null
                        }
                    </div>
                </div>
                <Modal
                    active={this.state.isShowModal}
                    onRequestClose={() => {this.setState({isShowModal: false})}}
                    actions={['cancel', this.handlePublicSubmit ]}
                    title="发公告"
                >
                    <div>
                        <TweetInput
                            ref={'publicTweetInput'}
                            handleFileChange={ (file, success) => {
                                // 请求上传地址
                                this.props.requestFeedImagesUploadUrl(res => {
                                    // 上传图片
                                    this.props.fileUpload({
                                        file: file.file.file,
                                        url: res.data.url,
                                        cb: () => {
                                            success({
                                                id: file.id,
                                                uuid: res.data.uuid,
                                                url: file.file.dataURL
                                            })
                                        }
                                    })
                                })
                            }}
                            onSubmit={::this.handleSubmit}
                            disabled={!this.state.addFeed}
                            atList={this.props.atList}
                            fetchAtList={keyword => this.props.fetchAtList({ keyword, type: 4 })}
                            label="说点什么.."
                            pic
                            multi
                            noBtn
                        />
                    </div>
                </Modal>
            </div>
        )
    }
}
